const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const User = require('./User');

// 消息通知模型定义
const Message = sequelize.define('Message', {
  // 主键ID
  id: {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false
  },
  
  // 消息类型: like, comment
  type: {
    type: DataTypes.STRING(20),
    allowNull: false,
    validate: {
      notEmpty: {
        msg: '消息类型不能为空'
      },
      isIn: {
        args: [['like', 'comment']],
        msg: '消息类型必须是like或comment'
      }
    }
  },
  
  // 发送消息的用户ID
  from_user_id: {
    type: DataTypes.BIGINT,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    },
    onDelete: 'CASCADE',
    onUpdate: 'CASCADE'
  },
  
  // 接收消息的用户ID
  to_user_id: {
    type: DataTypes.BIGINT,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    },
    onDelete: 'CASCADE',
    onUpdate: 'CASCADE'
  },
  
  // 消息内容
  content: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  
  // 关联的源ID（视频ID或评论ID）
  source_id: {
    type: DataTypes.BIGINT,
    allowNull: false
  },
  
  // 源类型: video, comment
  source_type: {
    type: DataTypes.STRING(20),
    allowNull: false,
    validate: {
      notEmpty: {
        msg: '源类型不能为空'
      },
      isIn: {
        args: [['video', 'comment']],
        msg: '源类型必须是video或comment'
      }
    }
  },
  
  // 是否已读: 0-未读, 1-已读
  is_read: {
    type: DataTypes.TINYINT,
    allowNull: false,
    defaultValue: 0,
    validate: {
      isIn: {
        args: [[0, 1]],
        msg: 'is_read必须是0或1'
      }
    }
  },
  
  // 创建时间
  created_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW
  },
  
  // 更新时间
  updated_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    onUpdate: DataTypes.NOW
  },
  
  // 删除时间（软删除）
  deleted_at: {
    type: DataTypes.DATE,
    allowNull: true,
    defaultValue: null
  }
}, {
  // 表配置
  tableName: 'message',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  deletedAt: 'deleted_at',
  paranoid: true,
  charset: 'utf8',
  collate: 'utf8_general_ci',
  indexes: [
    {
      name: 'idx_to_user',
      fields: ['to_user_id']
    },
    {
      name: 'idx_from_user',
      fields: ['from_user_id']
    },
    {
      name: 'idx_type',
      fields: ['type']
    },
    {
      name: 'idx_is_read',
      fields: ['is_read']
    }
  ]
});

// 关联关系
Message.belongsTo(User, {
  as: 'fromUser',
  foreignKey: 'from_user_id',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});

Message.belongsTo(User, {
  as: 'toUser',
  foreignKey: 'to_user_id',
  onDelete: 'CASCADE',
  onUpdate: 'CASCADE'
});

// 类方法：创建点赞消息
Message.createLikeMessage = async function(fromUserId, toUserId, sourceId, sourceType, content = null) {
  // 避免给自己发送消息
  if (fromUserId === toUserId) {
    return null;
  }
  
  // 生成默认内容
  if (!content) {
    if (sourceType === 'video') {
      content = '点赞了你的视频';
    } else if (sourceType === 'comment') {
      content = '点赞了你的评论';
    }
  }
  
  return await this.create({
    type: 'like',
    from_user_id: fromUserId,
    to_user_id: toUserId,
    content: content,
    source_id: sourceId,
    source_type: sourceType,
    is_read: 0
  });
};

// 类方法：创建评论消息
Message.createCommentMessage = async function(fromUserId, toUserId, sourceId, sourceType, content) {
  // 避免给自己发送消息
  if (fromUserId === toUserId) {
    return null;
  }
  
  return await this.create({
    type: 'comment',
    from_user_id: fromUserId,
    to_user_id: toUserId,
    content: content,
    source_id: sourceId,
    source_type: sourceType,
    is_read: 0
  });
};

// 类方法：获取用户的消息列表
Message.getUserMessages = async function(userId, type = null, page = 1, limit = 20) {
  const query = {
    where: {
      to_user_id: userId
    },
    include: [
      {
        model: User,
        as: 'fromUser',
        attributes: ['id', 'username', 'avatar', 'nickname']
      }
    ],
    order: [['created_at', 'DESC']],
    limit: parseInt(limit),
    offset: (parseInt(page) - 1) * parseInt(limit)
  };
  
  // 如果指定了消息类型
  if (type && ['like', 'comment'].includes(type)) {
    query.where.type = type;
  }
  
  return await this.findAndCountAll(query);
};

// 类方法：标记消息为已读
Message.markAsRead = async function(messageId, userId) {
  return await this.update(
    { is_read: 1 },
    {
      where: {
        id: messageId,
        to_user_id: userId
      }
    }
  );
};

// 类方法：标记所有消息为已读
Message.markAllAsRead = async function(userId, type = null) {
  const query = {
    where: {
      to_user_id: userId
    }
  };
  
  if (type && ['like', 'comment'].includes(type)) {
    query.where.type = type;
  }
  
  return await this.update(
    { is_read: 1 },
    query
  );
};

// 类方法：获取用户未读消息数量
Message.getUnreadCount = async function(userId, type = null) {
  const query = {
    where: {
      to_user_id: userId,
      is_read: 0
    }
  };
  
  if (type && ['like', 'comment'].includes(type)) {
    query.where.type = type;
  }
  
  return await this.count(query);
};

module.exports = Message;

// 导出到全局，方便其他模块使用
global.Message = Message;